package com.weixin.paleituo.activity;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.CountDownTimer;
import android.text.InputFilter;
import android.text.InputType;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.weixin.paleituo.R;
import com.weixin.paleituo.application.BaseApplication;
import com.weixin.paleituo.base.BasePersonActivity;
import com.weixin.paleituo.bean.RegisterProBean;
import com.weixin.paleituo.bean.StatusCode;
import com.weixin.paleituo.bean.UserInfoBean;
import com.weixin.paleituo.contans.Contans;
import com.weixin.paleituo.eventbus.LoginMessageEvent;
import com.weixin.paleituo.help.TextWatcherImp;
import com.weixin.paleituo.http.HttpUtil;
import com.weixin.paleituo.http.ProgressSubscriber;
import com.weixin.paleituo.http.RxHelper;
import com.weixin.paleituo.rxjava.ApiUtils;
import com.weixin.paleituo.util.AesUtil;
import com.weixin.paleituo.util.DeviceUuidFactory;
import com.weixin.paleituo.util.KeybordS;
import com.weixin.paleituo.util.LoadingDialogUtils;
import com.weixin.paleituo.util.LogUtils;
import com.weixin.paleituo.util.NetUtils;
import com.weixin.paleituo.util.PreferencesUtils;
import com.weixin.paleituo.util.StringUtils;
import com.weixin.paleituo.util.ToastUtils;
import com.weixin.paleituo.util.UIUtils;
import com.weixin.paleituo.view.LoginNewItemView;
import com.weixin.paleituo.view.RegisterProtocolPopupWindow;

import org.greenrobot.eventbus.EventBus;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

/**
 * Author yichao
 * Time  2017/11/28 14:45
 * Dest  注册页面
 */

public class RegisterActivity extends BasePersonActivity {



    @BindView(R.id.tv_comfire_activity_register)
    TextView mTvComfireActivityRegister;

    @BindView(R.id.loginNewItemView_phone_number_activity_register)
    LoginNewItemView mLoginNewItemViewPhoneNumberActivityRegister;
    @BindView(R.id.loginNewItemView_check_code_activity_register)
    LoginNewItemView mLoginNewItemViewCheckCodeActivityRegister;
    @BindView(R.id.loginNewItemView_password_activity_register)
    LoginNewItemView mLoginNewItemViewPasswordActivityRegister;
    @BindView(R.id.cb_protocol_activity_register)
    CheckBox mCbProtocolActivityRegister;
    @BindView(R.id.tv_protocol_activity_register)
    TextView mTvProtocolActivityRegister;
    private View mRegisteView;
    private EditText mEtPassword, mEtCheckCode, mEtPhoneNumber;
    private String mPhoneNumberStr;
    private TextView mMessageTextView;
    private String mIdCardStr;
    private String mCheckCodeStr;
    private String mPasswordStr;
    private RegisterProtocolPopupWindow mRegisterProtocolPopupWindow;
    private CountDownTimer mCountDownTimer;
   // private UpLoadPopuWindow mUpLoadPopuWindow;
    private Disposable mDisposableMsgCode, mDisposableRegister;
    private ImageView mIvIconPhoneNumber;
    private ImageView mIvIconPassword;
    private boolean isShowPassword;
    private Dialog mLoadingDialog;
    private String proContent;


    private boolean isRegisterSuccess=false;//是否注册成功
    @Override
    protected View getContentView(Context context) {
        mRegisteView = UIUtils.inflate(context, R.layout.activity_register);
        return mRegisteView;

    }

    @Override
    protected void initData() {
        super.initData();

        mViewline.setVisibility(View.GONE);
        mTvTitle.setVisibility(View.VISIBLE);
        mTvTitle.setText("注册");
        mEtPhoneNumber = mLoginNewItemViewPhoneNumberActivityRegister.getEtContent();
        mEtCheckCode = mLoginNewItemViewCheckCodeActivityRegister.getEtContent();
        mEtPassword = mLoginNewItemViewPasswordActivityRegister.getEtContent();
        mMessageTextView = mLoginNewItemViewCheckCodeActivityRegister.getTvGetMessage();
        mMessageTextView.setVisibility(View.VISIBLE);
        mLoginNewItemViewCheckCodeActivityRegister.setDefaultTvMessageStyle("发送验证码");
        mEtPhoneNumber.setInputType(InputType.TYPE_CLASS_PHONE);
        mEtPhoneNumber.setFilters(new InputFilter[]{new InputFilter.LengthFilter(11)});
        mEtPassword.setFilters(new InputFilter[]{new InputFilter.LengthFilter(20)});
        mEtPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
        mEtPassword.postInvalidate();
        mEtPassword.setSelection(mEtPassword.getText().length());
        mEtCheckCode.setFilters(new InputFilter[]{new InputFilter.LengthFilter(6)});
        mEtCheckCode.setInputType(InputType.TYPE_CLASS_NUMBER);

        mIvIconPhoneNumber = mLoginNewItemViewPhoneNumberActivityRegister.getIvIcon();
        mIvIconPhoneNumber.setImageResource(R.mipmap.del);


        mIvIconPassword = mLoginNewItemViewPasswordActivityRegister.getIvIcon();


        mIvIconPassword.setVisibility(View.VISIBLE);

        mIvIconPassword.setImageResource(R.mipmap.eyelash);

        isShowPassword = false;
    }

    @Override
    protected void initEvent() {
        super.initEvent();
        mEtPhoneNumber.addTextChangedListener(new TextWatcherImp() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                mPhoneNumberStr = s.toString();
                showConfireState(mPhoneNumberStr, mIdCardStr, mCheckCodeStr, mPasswordStr);

                showTvMessageStyle("发送验证码");
                if (StringUtils.isEmpty(mPhoneNumberStr)) {
                    mIvIconPhoneNumber.setVisibility(View.INVISIBLE);
                } else {
                    mIvIconPhoneNumber.setVisibility(View.VISIBLE);

                }
                if (mCountDownTimer != null) {
                    mCountDownTimer.cancel();
                }
            }
        });

        mEtCheckCode.addTextChangedListener(new TextWatcherImp() {


            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

                mCheckCodeStr = s.toString();
                showConfireState(mPhoneNumberStr, mIdCardStr, mCheckCodeStr, mPasswordStr);
            }
        });
        mEtPassword.addTextChangedListener(new TextWatcherImp() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                mPasswordStr = s.toString();
                showConfireState(mPhoneNumberStr, mIdCardStr, mCheckCodeStr, mPasswordStr);

            }
        });
        mMessageTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (!NetUtils.NetwrokIsUseful(RegisterActivity.this)) {
                    ToastUtils.makeText("网络不可用，请检查网络");
                    return;
                }

                //获取验证码
                ApiUtils.getApi().sendMsgCode(Contans.isEncrypt?AesUtil.aesEncrypt(mEtPhoneNumber.getText().toString().trim()):mEtPhoneNumber.getText().toString().trim(), Contans.SMSSING_REGISTER).subscribeOn(Schedulers.io())
                        .doOnSubscribe(new Consumer<Disposable>() {
                            @Override
                            public void accept(Disposable disposable) throws Exception {
                                if (mLoadingDialog == null) {


                                    mLoadingDialog = LoadingDialogUtils.createLoadingDialog(RegisterActivity.this, "");

                                }
                                LoadingDialogUtils.show(mLoadingDialog);


                                mLoginNewItemViewCheckCodeActivityRegister.setCountDownBeforTvMessageStyle();
                            }
                        }).subscribeOn(AndroidSchedulers.mainThread()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<StatusCode<String>>() {


                    @Override
                    public void onSubscribe(Disposable d) {

                        mDisposableMsgCode = d;
                    }

                    @Override
                    public void onNext(StatusCode<String> value) {
                        if (value.isFlag()) {
                            ToastUtils.makeText(value.getDetailMsg());
                            if (mCountDownTimer == null) {
                                mCountDownTimer = new CountDownTimer(60 * 1000, 1000) {
                                    @Override
                                    public void onTick(long millisUntilFinished) {
                                        mLoginNewItemViewCheckCodeActivityRegister.setCountDownTvMessageStyle(millisUntilFinished / 1000 + "");
                                    }

                                    @Override
                                    public void onFinish() {
                                        showTvMessageStyle("重新发送");
                                    }
                                };
                            }
                            mCountDownTimer.start();
                        } else {
                            ToastUtils.makeText(value.getDetailMsg());
                            showTvMessageStyle("发送验证码");
                        }
                        LogUtils.i(TAG, "注册获取验证码 ：：：" + value.toString());
                    }
                    @Override
                    public void onError(Throwable e) {
                        LogUtils.i(TAG, e.toString());
                        ToastUtils.makeText("发送验证码失败");
                        showTvMessageStyle("发送验证码");
                        LoadingDialogUtils.closeDialog(mLoadingDialog);
                    }

                    @Override
                    public void onComplete() {
                        LoadingDialogUtils.closeDialog(mLoadingDialog);

                    }
                });
            }
        });

        mCbProtocolActivityRegister.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    mCbProtocolActivityRegister.setBackgroundResource(R.mipmap.choice_hook);

                } else {
                    mCbProtocolActivityRegister.setBackgroundResource(R.mipmap.choice_square);

                }
            }
        });
        mIvIconPhoneNumber.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mEtPhoneNumber.setText("");

                if (mCountDownTimer != null) {
                    mCountDownTimer.cancel();
                }
            }
        });
        mIvIconPassword.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!isShowPassword) {
                    mIvIconPassword.setImageResource(R.mipmap.eye);
                    mEtPassword.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                    mEtPassword.postInvalidate();
                    mEtPassword.setSelection(mEtPassword.getText().length());
                    isShowPassword = true;
                } else {
                    mIvIconPassword.setImageResource(R.mipmap.eyelash);
                    //隐藏密码明文
                    mEtPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
                    mEtPassword.postInvalidate();
                    mEtPassword.setSelection(mEtPassword.getText().length());
                    isShowPassword = false;
                }
            }
        });
        mEtPassword.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId== 0 && KeybordS.isSoftInputShow(RegisterActivity.this)) {
                    KeybordS.closeKeybord(mEtPassword,RegisterActivity.this);

                    //关闭键盘
                    return true;//返回true,消费这个事件

                }

                return false;
            }
        });


    }

    /**
     * 判断获取验证码样式的判断
     */
    private void showTvMessageStyle(String tvContent) {

        if (UIUtils.isPhoneNumber(mPhoneNumberStr)) {
            //是手机号
            mLoginNewItemViewCheckCodeActivityRegister.setCheckPhoneSuceessTvMessageStyle(tvContent);
        } else {
            //不是手机号
            mLoginNewItemViewCheckCodeActivityRegister.setDefaultTvMessageStyle("发送验证码");
        }
    }

    /**
     * @param context
     */
    public static void startActivity(Context context) {
        Intent intent = new Intent(context, RegisterActivity.class);
        context.startActivity(intent);
    }


    @OnClick(R.id.tv_comfire_activity_register)
    public void onMTvComfireActivityRegisterClicked(final View view) {

        if (!mCbProtocolActivityRegister.isChecked()) {
            ToastUtils.makeText("请先同意协议");
            return;

        }

        if (!NetUtils.NetwrokIsUseful(RegisterActivity.this)) {
            ToastUtils.makeText(getString(R.string.check_internet));
            return;

        }

        if (!UIUtils.isPhoneNumber(mPhoneNumberStr)) {
            ToastUtils.makeText(R.string.check_phone_number);
            return;
        }

        if (!UIUtils.isPasswordFormat(mPasswordStr)) {
            ToastUtils.makeText(R.string.check_password_format);
            return;
        }


        ApiUtils.getApi().register(Contans.isEncrypt?AesUtil.aesEncrypt(mEtPhoneNumber.getText().toString().trim()):mEtPhoneNumber.getText().toString().trim(), Contans.isEncrypt?AesUtil.aesEncrypt(mEtPassword.getText().toString().trim()):mEtPassword.getText().toString().trim(), mEtCheckCode.getText().toString())
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(new Consumer<Disposable>() {
            @Override
            public void accept(Disposable disposable) throws Exception {

               /* if (mUpLoadPopuWindow == null) {

                    mUpLoadPopuWindow = new UpLoadPopuWindow(RegisterActivity.this);
                }
                mUpLoadPopuWindow.showAtLocation(view, 0, 0, Gravity.CENTER);
                mUpLoadPopuWindow.startAnimal();*/
               if (mLoadingDialog==null){
                   mLoadingDialog=LoadingDialogUtils.createLoadingDialog(RegisterActivity.this,"");

               }
               LoadingDialogUtils.show(mLoadingDialog);

                mTvComfireActivityRegister.setFocusable(false);
                mTvComfireActivityRegister.setEnabled(false);

            }
        }).observeOn(AndroidSchedulers.mainThread())
                .doOnNext(new Consumer<StatusCode<String>>() {
            @Override
            public void accept(StatusCode<String> stringStatusCode) throws Exception {

                ToastUtils.makeText(stringStatusCode.getDetailMsg());
            }
        }).observeOn(Schedulers.io())
                .flatMap(new Function<StatusCode<String>, ObservableSource<StatusCode<UserInfoBean>>>() {
                    @Override
                    public ObservableSource<StatusCode<UserInfoBean>> apply(StatusCode<String> stringStatusCode) throws Exception {
                        if (stringStatusCode.isFlag()){
                            //注册成功
                            isRegisterSuccess=true;
                            return ApiUtils.getApi().login(Contans.isEncrypt?AesUtil.aesEncrypt(mPhoneNumberStr):mPhoneNumberStr,Contans.isEncrypt?AesUtil.aesEncrypt(mPasswordStr):mPasswordStr, DeviceUuidFactory.getInstance(RegisterActivity.this).getDeviceUuid());
                        }else {
                            isRegisterSuccess=false;
                        }
                        return  Observable.empty();
                    }
                }).subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<StatusCode<UserInfoBean>>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        mDisposableRegister = d;

                    }

                    @Override
                    public void onNext(StatusCode<UserInfoBean> value) {
                        if (value.isFlag()) {
                            //mPhoneNumberStr,mPasswordStr
                            PreferencesUtils.getInstance().putString(Contans.username,mPhoneNumberStr);
                            PreferencesUtils.getInstance().putString(Contans.password,mPasswordStr);
                            BaseApplication.isLoginSuccess = true;
                            BaseApplication.sUserInfoBean = value.getData();

                            EventBus.getDefault().post(new LoginMessageEvent( BaseApplication.sUserInfoBean));

                            MainActivity.startActivity(RegisterActivity.this);
                        } else {
                            LoginActivity.startActivity(RegisterActivity.this,false);
                        }
                        ToastUtils.makeText(value.getDetailMsg());
                        showConfireState(mPhoneNumberStr, mIdCardStr, mCheckCodeStr, mPasswordStr);
                        LoadingDialogUtils.closeDialog(mLoadingDialog);
                        finish();
                    }

                    @Override
                    public void onError(Throwable e) {

                        LoadingDialogUtils.closeDialog(mLoadingDialog);
                        showConfireState(mPhoneNumberStr, mIdCardStr, mCheckCodeStr, mPasswordStr);
                        if (isRegisterSuccess){
                            //注册成功登录失败
                            ToastUtils.makeText("登录网络错误");

                            LoginActivity.startActivity(RegisterActivity.this,false);
                            finish();

                        }else {
                            //注册失败
                            ToastUtils.makeText("注册网络错误");
                        }
                    }

                    @Override
                    public void onComplete() {
                        LoadingDialogUtils.closeDialog(mLoadingDialog);
                        showConfireState(mPhoneNumberStr, mIdCardStr, mCheckCodeStr, mPasswordStr);
                    }
                });





    }

    /**
     * 显示确定的状态
     *
     * @param phoneNumberStr
     * @param idCardStr
     * @param checkCodeStr
     * @param passwordStr
     */
    private void showConfireState(String phoneNumberStr, String idCardStr, String checkCodeStr, String passwordStr) {
        if (!StringUtils.isEmpty(phoneNumberStr) && !StringUtils.isEmpty(checkCodeStr) && !StringUtils.isEmpty(passwordStr)&&UIUtils.isPasswordFormat(passwordStr)) {
            mTvComfireActivityRegister.setFocusable(true);
            mTvComfireActivityRegister.setEnabled(true);
        } else {
            mTvComfireActivityRegister.setFocusable(false);
            mTvComfireActivityRegister.setEnabled(false);
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mDisposableMsgCode != null && !mDisposableMsgCode.isDisposed()) {
            mDisposableMsgCode.dispose();
        }
        if (mDisposableRegister != null && !mDisposableRegister.isDisposed()) {
            mDisposableRegister.dispose();
        }
        if (mCountDownTimer != null) {
            mCountDownTimer.cancel();
        }
        LoadingDialogUtils.closeDialog(mLoadingDialog);
    }


    @OnClick(R.id.tv_protocol_activity_register)
    public void onViewClicked(final View view) {
        if (StringUtils.isEmpty(proContent)){
            Observable observable = ApiUtils.getApi().getRegisterPro(Contans.defaultToken)
                    .compose(RxHelper.getObservaleTransformer())
                    .doOnSubscribe(new Consumer<Disposable>() {
                        @Override
                        public void accept(Disposable disposable) throws Exception {

                            if (mLoadingDialog == null) {
                                mLoadingDialog = LoadingDialogUtils.createLoadingDialog(RegisterActivity.this, "");
                            }
                            mLoadingDialog.show();
                        }
                    }).subscribeOn(AndroidSchedulers.mainThread());
            HttpUtil.getInstance().toSubscribe(observable, new ProgressSubscriber<RegisterProBean>(this) {

                @Override
                protected void _onNext(StatusCode<RegisterProBean> registerProBeanStatusCode) {
                    LoadingDialogUtils.closeDialog(mLoadingDialog);

                    RegisterProBean dataProBean = registerProBeanStatusCode.getData();

                    proContent=dataProBean.getContent();
                    if (!StringUtils.isEmpty(proContent)){
                        //弹出协议
                        if (mRegisterProtocolPopupWindow == null) {
                            mRegisterProtocolPopupWindow = new RegisterProtocolPopupWindow(RegisterActivity.this,proContent);
                        }
                        mRegisterProtocolPopupWindow.showAtLocation(view, Gravity.CENTER, 0, 0);
                    }
                }

                @Override
                protected void _onError(String message) {
                    ToastUtils.makeText(message);
                    LoadingDialogUtils.closeDialog(mLoadingDialog);

                }

            },"",lifecycleSubject,false,true);

        }else {
            //弹出协议
            if (mRegisterProtocolPopupWindow == null) {
                mRegisterProtocolPopupWindow = new RegisterProtocolPopupWindow(this,proContent);
            }
            mRegisterProtocolPopupWindow.showAtLocation(view, Gravity.CENTER, 0, 0);
        }


    }
}
